package back_0417;

import io.netty.handler.codec.http.*;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Auth: bruce-sha
 * Date: 2015/4/8
 */
public class RequestRouter {

    final Set<String> selectedPaths;
    HttpRequest request;

    private RequestRouter(String... rawPaths) {
        this.selectedPaths = new CopyOnWriteArraySet<>();
        for (String rawPath : rawPaths) {
            if (rawPath == null) continue;
            selectedPaths.add(standardizePath(rawPath));
        }
    }

//    private RequestRouter(HttpRequest request) {
//        this.request = request;
//    }

    private String standardizePath(String rawPath) {
        rawPath = rawPath.replace('\\', '/');
        while (rawPath.startsWith("/")) rawPath = rawPath.substring(1);
        while (rawPath.endsWith("/")) rawPath = rawPath.substring(0, rawPath.length() - 1);
        return rawPath;
    }

    public void deal(Handler handler) {
        assert request != null;

        final String uri = request.uri();
        final QueryStringDecoder query = new QueryStringDecoder(uri);

        String requestPath = query.path();
        String standardPath = standardizePath(requestPath);

        if (selectedPaths.contains(standardPath)) handler.handle(standardPath);
    }


    public static interface Handler {
        void handle(String path);
    }

    public static void main(String[] args) {

        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/hello/");

        RequestRouter.select("/hello").route(request).deal(path ->
        {
            System.out.println("request path is " + path);
        });

    }

    public static RequestRouter select(String... paths) {
        return new RequestRouter(paths);
    }

    public RequestRouter route(HttpRequest request) {
        this.request = request;
        return this;
    }


//    public static class RequestRouters {
//        public static RequestRouter router(HttpRequest request) {
//            return new RequestRouter(request);
//        }
//    }
}
